//
// Created by tacom on 22-9-6.
// 此算法的行为表现和python不一致，不要删除本界面的debug代码
// 坑点总结如下：
//  1. python -> cxx:
//      - 使用的应该是实体，即为 xxx.copy()如果是roi传输的时候概率撕裂(不知道为啥)
//      - 使用pybind11传输的时候，应该使用8UC1, 也就是指名通道，否则解析回来的时候像素点位置莫名有偏移
//  2. c++ 数值统计：
//      - 需要时刻判断类型是否符合，比如uchar类型的1 != 1, 需要写成 uchar(x, y) == uchar(1)
//      - 或者说处理的时候只能使用一种数据类型，别强转，容易找不到bug
//  3. c++ 双重循环删除bug:
//      - 内层循环删除后，数据整体前移，且删除点在外层循环的外面，导致外层循环跳格子
//

#include "intersection.h"
#include "algorithm"
#include "cmath"


intersection::INTERSECTIONS intersection::GetSkeletonIntersection(cv::Mat &skeleton) {
    cv::Mat image = skeleton / 255;  // type is: 8U
    INTERSECTIONS intersections;

    for (int x = 1; x < image.rows - 1; ++x){
        for(int y = 1; y < image.cols - 1; ++y){
            if (image.at<uchar>(x, y) == uchar(1)){
                EACH_INTERSECTIONS neighbour = intersection::GetNeighbours(x, y, image);
                auto it = std::find(validIntersection.begin(), validIntersection.end(), neighbour);
                if (it != validIntersection.end()){
                    intersections.push_back(std::make_pair(y, x));
                }
            }
        }
    }


    for(std::vector<POINT>::iterator i = intersections.begin(); i != intersections.end(); ++i){
        for(std::vector<POINT>::iterator j = intersections.begin(); j != intersections.end(); ){
            POINT point1 = *i, point2 = *j;
            int p1_x = point1.first, p1_y = point1.second;
            int p2_x = point2.first, p2_y = point2.second;
            if ((pow(p1_x - p2_x, 2) + pow(p1_y - p2_y, 2)) < 64 && point1 != point2){
                j = intersections.erase(j);
                if (j < i){
                    --i;
                }
            }else{
                ++j;
            }
        }
    }

    return intersections;
}

intersection::EACH_INTERSECTIONS intersection::GetNeighbours(int x, int y, cv::Mat &img) {
    int x_1 = x - 1, y_1 = y - 1, x1 = x + 1, y1 = y + 1;
    return intersection::EACH_INTERSECTIONS{
        img.at<u_char>(x_1, y), img.at<u_char>(x_1, y1), img.at<uchar>(x, y1),
        img.at<uchar>(x1, y1), img.at<uchar>(x1, y), img.at<uchar>(x1, y_1),
        img.at<uchar>(x, y_1), img.at<uchar>(x_1, y_1)
    };
}